package com.cssl.config;
import com.cssl.job.MyJob;
import com.cssl.utils.MyAdaptableJobFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

//quartz配置文件
@Configuration
public class QuartzConfig {


    //1.创建job对象
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean(){
        JobDetailFactoryBean factory = new JobDetailFactoryBean();
        //关联我们定义的job类
        factory.setJobClass(MyJob.class);
       AdaptableJobFactory a=null;// 业务逻辑层  空指针异常的原因 createJobInstance

        //1.解决办法  继承AdaptableJobFactory 重写createJobInstance  先将myjob类加入SprigIOC

        return factory;
    }


    //2.创建trigger对象  简单trigger

//    @Bean
//    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
//
//        SimpleTriggerFactoryBean factory=new SimpleTriggerFactoryBean();
//        //关联我们的任务
//        factory.setJobDetail(jobDetailFactoryBean.getObject());
//        //设置触发时间
//        factory.setRepeatInterval(1000);//参数是毫秒数
//       factory.setRepeatCount(5);//重复次数，如果不设置 ，默认是永远
//
//        return  factory;
//
//    }


    /**
     * 使用cron表达式
     *
     * */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean factory=new CronTriggerFactoryBean();
        factory.setJobDetail(jobDetailFactoryBean.getObject());
        factory.setCronExpression("0/10 * * * * ?");
        return  factory;

    }

    //3.创建scheduler对象
   // SimpleTriggerFactoryBean simpleTriggerFactoryBean


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean simpleTriggerFactoryBean){
        SchedulerFactoryBean factory=new SchedulerFactoryBean();
        //关联 trigger
        factory.setTriggers(simpleTriggerFactoryBean.getObject());

        return factory;
    }


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean simpleTriggerFactoryBean, MyAdaptableJobFactory myAdaptableJobFactory){
        SchedulerFactoryBean factory=new SchedulerFactoryBean();
        //关联 trigger
        factory.setTriggers(simpleTriggerFactoryBean.getObject());
        //可以重新设置新job
        factory.setJobFactory(myAdaptableJobFactory);
        return factory;
    }

}
